package logic

import (
	"api/appconfig"
	"context"
	jwt "github.com/golangblogs/gojwt"
	"user_srv/user"

	"api/internal/svc"
	"api/internal/types"

	"github.com/zeromicro/go-zero/core/logx"
)

type LoginLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewLoginLogic(ctx context.Context, svcCtx *svc.ServiceContext) *LoginLogic {
	return &LoginLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *LoginLogic) Login(req *types.Loginrequest) (resp *types.Response, err error) {
	login, err := l.svcCtx.Userrpc.Login(l.ctx, &user.LoginRequest{
		Account: req.Account,
	})
	if err != nil {
		return &types.Response{
			Code:    500,
			Message: "登录失败",
			Data:    nil,
		}, nil
	}
	newJwt := jwt.NewJWT(appconfig.ConfigData.Jwt.SecretKey)
	claims := jwt.CustomClaims{ID: uint(login.UserId)}
	token, err := newJwt.CreateToken(claims)

	return &types.Response{
		Code:    200,
		Message: "登录成功",
		Data: map[string]interface{}{
			"token": token,
		},
	}, nil
}
